import os.path
import os
import zipfile

def zip(target, source, env):
    zf = zipfile.ZipFile(str(target[0]), 'w')
    root = env.get("ZIPROOT", ".")
    vir_root = env.get("ZIPVIRROOT", ".")
    for s in source:
        if s.isdir():
            for dirpath, dirnames, filenames in os.walk(str(s)):
                for fname in filenames:
                    path = os.path.join(dirpath, fname)
                    if os.path.isfile(path):
                        zf.write(path, os.path.normpath(
                            os.path.join(vir_root,
                            os.path.relpath(path, root))))
        else:
            path = str(s)
            zf.write(path, os.path.normpath(
                os.path.join(vir_root,
                os.path.relpath(path, root))))
    zf.close()

bld = Builder(action = zip,multi = 1)

SRC_DIR = "build"

common_files = [os.path.join(SRC_DIR, i) for i in
               ["utils.cpp"
               ]]
tracker_files = [os.path.join(SRC_DIR, i) for i in
                ["AffineTracker.cpp",
                 "CameraThread.cpp",
                 "ElasticModel.cpp",
                 "EyeDetector.cpp",
                 "GLThread.cpp",
                 "HeadPosition.cpp",
                 "oflow.cpp",
                 "tracker.cpp",
                ]]
tracker_res = [  "target.png",
                 "hc_eyes.xml",
                 "hc_face.xml"
              ]
tracker_res_deps = [os.path.join("hinapt/bin", i) for i in tracker_res]
trainer_files = [os.path.join(SRC_DIR, i) for i in
                ["filesystem.cpp",
                 "train.cpp",
                 "trainer.cpp",
                 "classifierTh.cpp",
                 "detectorTh.cpp",
                 "thresholdFeature.cpp",
                ]]
check_files = [os.path.join(SRC_DIR, i) for i in
             ["check.cpp"
             ]]

external_libs = ["sfml-system",
                 "sfml-window",
                 "sfml-graphics",
                 "GLU",
                 "GL",
                 "opencv_core",
                 "opencv_imgproc",
                 "opencv_highgui",
                 "opencv_objdetect",
                 "boost_filesystem",
                 ]

VariantDir(SRC_DIR, 'hinapt', duplicate=False)
env = Environment(ENV = os.environ)


env['BUILDERS']['Zip'] = bld

flags = env.ParseFlags("-fopenmp")
flags["LINKFLAGS"] += flags["CCFLAGS"]
env.MergeFlags(flags)

flags = env.ParseFlags("-O3")
env.MergeFlags(flags)

env.Append(CPPPATH=["hinapt"])
env.Append(LIBS=external_libs)

for i in tracker_res:
    env.Command(os.path.join("hinapt/bin", i),
                os.path.join("hinapt", i),
                Copy("$TARGET", "$SOURCE")
    )


tracker = env.Program('hinapt/bin/tracker', common_files+tracker_files)
env.Precious(tracker)
env.Depends(tracker, tracker_res_deps)
env.NoClean(tracker_res_deps)
trainer = env.Program('hinapt/bin/trainer', common_files+trainer_files)
env.Precious(trainer)
libcheck = env.SharedLibrary('hinapt/bin/check',
            common_files+trainer_files+check_files)
env.Precious(libcheck)


source_folders = ["hinapt", "hinapt/scripts/img_getter"]
source_exts = (".py", ".cpp", ".hpp")
source_files = []
for p in source_folders:
    l = os.listdir(p)
    source_files.extend([os.path.join(p, i) for i in l
        if os.path.splitext(i)[1] in source_exts])
source_files = Flatten(source_files)

export = env.Command('sources.pdf',
    source_files, [ Mkdir("hinapt/export"),
                    "cd hinapt && ./export.py",
                    Move("sources.pdf", "hinapt/export/export.pdf")
                  ])
env.Clean(export, ["hinapt/export"])
env.NoClean(export)
doc = env.Command(['doc/html', 'doc/latex/refman.pdf'],                 source_files,
                            ["doxygen doxygen.conf",
                            "cd doc/latex && make",
                            Move("doc/refman.pdf", "doc/latex/refman.pdf"),
                            Delete("doc/latex")])

env.NoClean("doc/html", "doc/refman.pdf")

readme = env.Command("README.html", "README.rst",
    "rst2html $SOURCE > $TARGET")

zip_export = source_files + [
    "doxygen.conf",
    "README.rst",
    "README.html",
    "SConstruct",
    "hinapt/hinapt.cbp",
    "hinapt/LICENSE",
    "hinapt/scripts/img_getter/words"
    ] + [
    os.path.join("hinapt", i) for i in tracker_res
    ]
doc_export = ["doc/html/", "doc/refman.pdf","sources.pdf"]

all_export = zip_export + doc_export

for i in all_export:
    c = env.Command(os.path.join(".tmp_dist", i), i,
        [Copy("$TARGET", "$SOURCE")])
Execute(Delete(".tmp_dist/doc/html"))

zip_export_sources = [os.path.join(".tmp_dist", i)
    for i in zip_export]
zip_export_doc = [os.path.join(".tmp_dist", i)
    for i in doc_export]


env.NoClean("dist/hinapt.zip")

env["ZIPROOT"] = ".tmp_dist"
env["ZIPVIRROOT"] = "hinapt"

base_zip = env.Zip("dist/hinapt.zip", zip_export_sources)
doc_zip = env.Zip("dist/hinapt.zip", zip_export_doc)
Clean(base_zip, ".tmp_dist")

env.Alias("zip", [base_zip, doc_zip])
env.Alias("tracker", "hinapt/bin/tracker")
env.Alias("trainer", "hinapt/bin/trainer")
env.Alias("check", libcheck)
env.Alias("export", export)
env.Alias("all-bin", ["tracker", "trainer", "check"])
env.Alias("all", ["all-bin", "doc", "export"])
env.Alias("readme", readme)


env.Default("tracker")
